import { listInterfaceInfoByPageUsingGET } from '@/services/yuapi-backend/interfaceInfoController';
// @ts-ignore
// @ts-ignore
// @ts-ignore
import {
  buyInterfaceCountNumUsingPOST,
  getInterfaceAndLeftUsingPOST,
} from "@/services/yuapi-backend/userInterfaceInfoController";
import { PlusOutlined } from '@ant-design/icons';
import {ActionType, PageContainer, ProColumns} from '@ant-design/pro-components';
import { ProTable } from '@ant-design/pro-table/lib';
import { Button, List, message, Modal } from 'antd';
import React, {useEffect, useRef, useState} from 'react';
// const actionRef = useRef<ActionType>();
/**
 * 主页
 * @constructor
 */
const Index: React.FC = () => {
  type Props = {
    columns: ProColumns<API.UserInterfaceInfo>[];
    onCancel: () => void;
    onSubmit: (values: API.UserInterfaceInfoBuyRequest) => Promise<void>;
    visible: boolean;
  };
  const CreateModal: React.FC<Props> = (props) => {
    const { visible, columns, onCancel, onSubmit } = props;
    return (
      <Modal visible={visible} footer={null} onCancel={() => onCancel?.()}>
        <ProTable
          type="form"
          columns={columns}
          onSubmit={async (value) => {
            try {
              const success = await buyInterfaceCountNumUsingPOST(value);
              if (success) {
                message.success('购买成功');
                // actionRef.current?.reload();
                window.location.reload();
              }
            } catch (error: any) {
              message.error(error.message);
            }
            handleModalOpen(false);
          }}
        />
      </Modal>
    );
  };
  const [loading, setLoading] = useState(false);
  const [createModalOpen, handleModalOpen] = useState<boolean>(false);
  const [list, setList] = useState<API.InterfaceInfo[]>([]);
  const [total, setTotal] = useState<number>();

  const loadData = async (current = 1, pageSize = 10) => {
    setLoading(true);
    try {
      const res: any = await listInterfaceInfoByPageUsingGET({ current, pageSize });
      setList(res?.data?.records ?? []);
      setTotal(res?.data?.total ?? 0);
    } catch (error: any) {
      message.error('请求失败,' + error.message);
      return false;
    }
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, []);

  const columns: ProColumns<API.UserInterfaceInfo>[] = [
    {
      title: '用户ID',
      dataIndex: 'userId',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '快填！',
          },
        ],
      },
    },
    {
      title: '接口ID',
      dataIndex: 'interfaceInfoId',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '快填！',
          },
        ],
      },
    },
    {
      title: '购买次数',
      dataIndex: 'num',
      valueType: 'text',
      formItemProps: {
        rules: [
          {
            required: true,
            message: '快填！',
          },
        ],
      },
    },
  ];

  const infoColumns = [
    {
      title: '所持有接口',
      dataIndex: 'interfaceName',
      key: 'age',
    },
    {
      title: '接口剩余调用次数',
      dataIndex: 'leftNum',
      key: 'address',
    },
  ];
  return (
    <PageContainer title="API开放平台">
      <List
        className="my-list"
        loading={loading}
        itemLayout="horizontal"
        dataSource={list}
        renderItem={(item) => {
          const apiLink = `/interface_info/${item.id}`;
          return (
            <List.Item
              actions={[
                <a key={item.id} href={apiLink}>
                  查看
                </a>,
              ]}
            >
              <List.Item.Meta
                title={<a href={apiLink}>{item.name}</a>}
                description={item.description}
              />
            </List.Item>
          );
        }}
        pagination={{
          pageSize: 5,
          total,
          onChange(page, pageSize) {
            loadData(page, pageSize);
          },
        }}
      />
      <Button
        type="primary"
        key="primary"
        onClick={() => {
          handleModalOpen(true);
        }}
      >
        <PlusOutlined /> 购买接口
      </Button>
      <CreateModal
        columns={columns}
        onCancel={() => {
          handleModalOpen(false);
        }}
        onSubmit={(values) => {}}
        visible={createModalOpen}
      ></CreateModal>




      <ProTable<API.UserInterfaceInfoVO>
        headerTitle={'用户所持信息'}
        search={{
          labelWidth: 120,
        }}

        request={async () => {
          const res: any = await getInterfaceAndLeftUsingPOST({userId:2});
          if (res.data) {
            console.log(res.data)
            return {
              data: res?.data,
              success: true,
            };
          } else {
            return {
              data: [],
              success: false,
            };
          }
        }}
        columns={infoColumns}
      />
    </PageContainer>
  );
};

export default Index;
